<?php

namespace App\Observers\Train;

use App\Facades\StationsGeoFacade;
use App\Models\Train\Stations\TrainStation;
use App\Trip\Train\Providers\Official\TrainQuery;
use Illuminate\Contracts\Filesystem\FileNotFoundException;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use function config;

class TrainStationObserver
{
    public function creating(TrainStation $station)
    {
        $station->initial = Str::upper($station->initial);
        $this->prefixOp($station);

    }

    /**
     * 前置操作
     * @param TrainStation $station
     * @return void
     * @throws FileNotFoundException
     */
    private function prefixOp(TrainStation $station): void
    {

        // isOfficial 官方站点
        $q                    = new TrainQuery();
        $content              = $q->getStationFileContent();
        $station->is_official = Str::contains($content, $station->getStationCode()) ? 1 : 0;

        // 香港地区
        if ($station->isHk()) {
            $station->state = 1; // 暂时关闭
        }

        // 匹配状态 为未匹配城市
        if (!$station->adcode) {
            $station->match_state = 0;
        }

        // 暂停营业
//        if (Str::contains($station->amap_name, '暂停营业')) {
//
//        }

    }

    public function updating(TrainStation $station)
    {
        $station->initial = Str::upper($station->initial);
        $this->prefixOp($station);
    }


    /**
     * Handle the User "created" event.
     *
     * @param TrainStation $station
     * @return void
     */
    public function created(TrainStation $station)
    {
        $cache_key_code = "Train:StationCode:{$station->getStationCode()}";
        $cache_key_name = "Train:StationName:{$station->getStationName()}";
        Cache::put($cache_key_code, $station, 30 * config('trip.ttl.day'));
        Cache::put($cache_key_name, $station, 30 * config('trip.ttl.day'));
        StationsGeoFacade::addGeoByStation($station);
    }

    /**
     * Handle the User "updated" event.
     *
     * @param TrainStation $station
     * @return void
     */
    public function updated(TrainStation $station)
    {
        $cache_key_code = "Train:StationCode:{$station->getStationCode()}";
        $cache_key_name = "Train:StationName:{$station->getStationName()}";
        Cache::put($cache_key_code, $station, 30 * config('trip.ttl.day'));
        Cache::put($cache_key_name, $station, 30 * config('trip.ttl.day'));
        StationsGeoFacade::addGeoByStation($station);
    }

    public function deleted(TrainStation $station)
    {
        $cache_key_code = "Train:StationCode:{$station->getStationCode()}";
        $cache_key_name = "Train:StationName:{$station->getStationName()}";
        Cache::forget($cache_key_code);
        Cache::forget($cache_key_name);
        StationsGeoFacade::delGeo($station->getStationCode());
    }
}
